package net.mayee.alice.tags;

import jetbrick.template.JetAnnotations;
import jetbrick.template.runtime.JetTagContext;
import net.mayee.alice.entity.menu.NavbarMenus;
import net.mayee.alice.entity.menu.nanbar.Logo;
import net.mayee.alice.entity.menu.nanbar.Logout;
import net.mayee.alice.entity.menu.nanbar.NavbarMenu;
import net.mayee.alice.entity.menu.nanbar.Profile;
import net.mayee.alice.entity.menu.sidebar.SidebarMenu;
import net.mayee.alice.filter.ShiroAdminDbRealm;
import net.mayee.alice.functions.base.BaseFunctions;
import net.mayee.alice.functions.ui.UIFunction;
import net.mayee.common.MenuHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.io.IOException;
import java.util.List;

@JetAnnotations.Tags
public class MenuTag {

    public static void printNavbarMenu(JetTagContext ctx) throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("<div class=\"page-header md-shadow-z-1-i navbar navbar-fixed-top\">")
                .append("<div class=\"page-header-inner\">")
                .append("<div class=\"container-fluid\">");

        NavbarMenus navbarMenus = MenuHelper.getInstance().getNavbarMenus();
        /* logo */
        sb.append(buildLogo(navbarMenus.getLogo()));

        /* profile */
        sb.append(buildProfile(navbarMenus.getProfile()));
        sb.append("</ul></li>");

        /* logout */
        sb.append(buildLogout(navbarMenus.getLogout()));
        sb.append("</ul></div></div></div></div>");
        ctx.getWriter().print(sb.toString());
    }

    private static String buildProfile(Profile profile) {
        StringBuilder sb = new StringBuilder();

        /* currentUser */
        Subject currentUser = SecurityUtils.getSubject();
        ShiroAdminDbRealm.ShiroUser shiroUser = (ShiroAdminDbRealm.ShiroUser) currentUser.getPrincipal();

        sb.append("<div class=\"top-menu\">")
                .append("<ul class=\"nav navbar-nav pull-right\">")
                .append("<li class=\"dropdown dropdown-user\"><a href=\"javascript:;\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" data-hover=\"dropdown\" data-close-others=\"true\"><img alt=\"\" id=\"miniPhoto\" class=\"img-circle\" src=\"")
                .append(BaseFunctions.getPath()).append("/").append(shiroUser.getPhoto()).append("\"/>")
                .append("<span class=\"username username-hide-on-mobile\"> ");

        String viewName = shiroUser.getName();
        if ("login_name".equals(profile.getViewName())) {
            viewName = shiroUser.getLoginName();
        }

        sb.append(viewName)
                .append(" </span><i class=\"fa fa-angle-down\"></i>")
                .append("</a>")
                .append("<ul class=\"dropdown-menu dropdown-menu-default\">");

        List<NavbarMenu> navbarMenuList = profile.getNavbarMenuList();
        for (NavbarMenu nbm : navbarMenuList) {
            String nbmId = nbm.getId();
            if("logOut".equals(nbmId)){
                sb.append("<li><a data-text=\"");
                sb.append(BaseFunctions.getMessage("net.mayee.alice.alert.logout"));
                sb.append("\" href=\"javascript:;\" ");
            }else{
                sb.append("<li><a href=\"")
                        .append(BaseFunctions.getPath())
                        .append(nbm.getHref())
                        .append("\" ");
            }
            sb.append(" id=\"")
                    .append(nbmId)
                    .append("\"><i class=\"")
                    .append(nbm.getIcon())
                    .append("\"></i> ")
                    .append(BaseFunctions.getMessage(nbm.getMessageKey(), nbm.getName()))
                    .append(" </a></li>");

            if (nbm.getHadBottomLine() == true) {
                sb.append("<li class=\"divider\"></li>");
            }
        }

        return sb.toString();
    }

    private static String buildLogo(Logo logo) {
        StringBuilder sb = new StringBuilder();

        sb.append("<div class=\"page-logo\">");
        sb.append("<a href=\"");

        /* href */
        sb.append(BaseFunctions.getPath());
        sb.append(logo.getHref());
        sb.append("\">");

        /* img */
        sb.append("<img src=\"");
        sb.append(BaseFunctions.getBasePath());
        sb.append(logo.getImgSrc());
        sb.append("\" ");

        /* alt */
        sb.append("alt=\"");
        sb.append(logo.getAlt());
        sb.append("\" class=\"logo-default\"/>");
        sb.append("</a>");

        sb.append("</div>");
        return sb.toString();
    }

    private static String buildLogout(Logout logout) {
        StringBuilder sb = new StringBuilder();

        sb.append("<li class=\"dropdown dropdown-quick-sidebar-toggler\">")
                .append("<a href=\"")
                .append(BaseFunctions.getPath())
                .append(logout.getHref())
                .append("\" class=\"dropdown-toggle\">")
                .append("<i class=\"")
                .append(logout.getIcon())
                .append("\"></i></a></li>");
        return sb.toString();
    }

    public static void printSidebarMenu(JetTagContext ctx) throws IOException {

        StringBuilder sb = new StringBuilder();
        sb.append("<div class=\"page-sidebar-wrapper\">")
                .append("<div class=\"page-sidebar navbar-collapse collapse\">")
                .append("<ul class=\"page-sidebar-menu\" data-keep-expanded=\"false\" data-auto-scroll=\"true\" data-slide-speed=\"200\">")
                .append("<li class=\"sidebar-toggler-wrapper\">")
                .append("<div class=\"sidebar-toggler\"></div>")
                .append("</li>");

        List<SidebarMenu> sidebarMenuList = MenuHelper.getInstance().getSidebarMenus().getSidebarMenu();
        for (int i = 0, n = sidebarMenuList.size(); i < n; i++) {

            SidebarMenu sbm = sidebarMenuList.get(i);

            String activeStr = "";
            if (sbm.isActive()) {
                activeStr = " active";
                if (sbm.isHadSubMenu()) {
                    activeStr = " active open";
                }
            }

            if (i == 0) {
                sb.append("<li class=\"start").append(activeStr).append("\">");
            } else if (i == n) {
                sb.append("<li class=\"last").append(activeStr).append("\">");
            } else {
                sb.append("<li class=\"").append(activeStr).append("\">");
            }

            /* 先遍历子菜单，并收集权限信息，当所有子菜单都无权限时，父菜单也不显示 */
            String subMenuString = buildSidebarSubMenu(sbm);
            if(subMenuString != null){
                sb.append(buildSidebarMenu(sbm));
                sb.append(subMenuString);
            }

            sb.append("</li>");
        }

        sb.append("</ul></div></div");
        ctx.getWriter().print(sb.toString());
    }

    private static String buildSidebarMenu(SidebarMenu sbm) {
        StringBuilder sb = new StringBuilder();

        /* href */
        if (!sbm.isHadSubMenu() && sbm.getHref() != null) { // 没有子菜单并且带有HREF属性
            sb.append("<a href=\"").append(BaseFunctions.getPath()).append(sbm.getHref()).append("\">");
        } else {
            sb.append("<a href=\"javascript:;\">");
        }

        /* icon */
        sb.append("<i class=\"").append(sbm.getIcon()).append("\"></i>");

        /* name */
        sb.append("<span class=\"title\">")
                .append(BaseFunctions.getMessage(sbm.getMessageKey(), sbm.getName()))
                .append("</span>");

        if (sbm.isHadSubMenu() && sbm.isActive()) {
            sb.append("<span class=\"selected\"></span>");
            sb.append("<span class=\"arrow open\"></span>");
        } else if (sbm.isActive()) {
            sb.append("<span class=\"selected\"></span>");
        } else if (sbm.isHadSubMenu()) {
            sb.append("<span class=\"arrow\"></span>");
        }
        sb.append("</a>");

        return sb.toString();
    }

    private static String buildSidebarSubMenu(SidebarMenu sbm) {
        /* 所有子菜单都无权限 */
        boolean noPermissedForAllSubMenu = true;
        StringBuilder sb = new StringBuilder();

        if (sbm.isHadSubMenu()) {
            sb.append("<ul class=\"sub-menu\">");

            List<SidebarMenu> subMenuList = sbm.getSubMenuList();
            for (SidebarMenu subMenu : subMenuList) {
                String subMenuId = subMenu.getId();
                /* 权限验证 */
                if(UIFunction.isPermission(subMenuId + ":R")){
                    noPermissedForAllSubMenu = false;
                    if (subMenu.isActive()) {
                        sb.append("<li class=\"active\">");
                    } else {
                        sb.append("<li>");
                    }
                    sb.append("<a href=\"").append(BaseFunctions.getPath()).append(subMenu.getHref()).append("\">");
                    /* icon */
                    sb.append(" <i class=\"").append(subMenu.getIcon()).append("\"></i> ");
                    sb.append(BaseFunctions.getMessage(subMenu.getMessageKey(), subMenu.getName())).append("</a></li>");
                }
            }

            if(noPermissedForAllSubMenu){
                return null;
            }

            sb.append("</ul>");
        }
        return sb.toString();
    }

}
